package trafficcontrol

import (
	"sync"

	"github.com/zeromicro/go-zero/core/conf"
)

var (
	serviceGray = make(map[string]GrayConfig)
	ControlLock sync.RWMutex
	c           GrayConfigsInfo
)

const (
	SwitchClose             = 0 // 关闭灰度发布
	SwitchWhite             = 1 // 白名单
	SwitchCertainProportion = 2 // 一定比例的灰度发布
	SwitchAll               = 3 // 全量灰度
)

func GetServiceGray() map[string]GrayConfig {
	return serviceGray
}

func StartTrafficControl(cfg NacosConfig) {
	nacos := NewNacos(cfg)
	serviceConfigContent := nacos.InitConfig(func(data string) {
		err := conf.LoadFromJsonBytes([]byte(data), &c)
		if err != nil {
			panic(err)
		}

		// 使用写锁
		ControlLock.Lock()
		serviceGray = make(map[string]GrayConfig)
		for _, grayConfig := range c.GrayConfigsInfo {
			serviceGray[grayConfig.GrayService] = grayConfig
		}
		ControlLock.Unlock()

	})
	err := conf.LoadFromJsonBytes([]byte(serviceConfigContent), &c)
	if err != nil {
		panic(err)
	}
	// 使用写锁
	ControlLock.Lock()
	serviceGray = make(map[string]GrayConfig)
	for _, grayConfig := range c.GrayConfigsInfo {
		serviceGray[grayConfig.GrayService] = grayConfig
	}
	ControlLock.Unlock()

	/*
		threading.GoSafe(func() {
			for {
				logx.Debugf("serviceGray: %+v", serviceGray)
				time.Sleep(10 * time.Second)
			}

		})

	*/

}

func Contains(slice []string, item string) bool {
	for _, s := range slice {
		if s == item {
			return true
		}
	}
	return false
}
